#!/bin/bash

## Get formated bibtex entrys from one or more citeulike IDs
##
## Alternatively, if $1 is a file, treat it as latex error log (.blg) and look
## for citeulike IDs to be dumped as bibtex.
##
## Uses bibtool to format/normalize the bibtex and generate a custom bibtex key.

repo=/home/pepe/files/lispler/citeulike
bibtool_res=/home/pepe/files/lispler/git/configs/bibtex/bibtool_keys_marwin.rc

if [ -f "$1" ]; then
  for id in $(grep "Warning--I didn't find a database entry for" "$1"|sed s/"\"$"//|sed s/".*\""//); do
    test 0 -lt "$id" > /dev/null 2>&1 || continue;

    if [ -f $repo/$id/$id.bib ]; then
      bibtool -r $bibtool_res $repo/$id/$id.bib
    else
      echo "No such bibtex ID $key"
    fi
  done
else
  for id in $*; do
    bibtool -r $bibtool_res $repo/$id/$id.bib
    echo
  done
  echo

fi
